<?php


namespace app\common\command;


use app\api\service\OrderService;
use app\BaseController;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\console\input\Argument;
use think\facade\Db;

class Order extends Command
{
    protected function configure()
    {
        $this->setName('order')
            ->addArgument('action', Argument::OPTIONAL, "执行动作")
            ->setDescription('订单');
    }

    protected function execute(Input $input, Output $output)
    {
        $action = $input->getArgument('action');
        if (empty($action)) {
            $action = 'index';
        }
        try {
            if (!method_exists($this, $action)) {
                throw new \Exception("未找到{$action}方法", 0);
            }
            call_user_func([$this, $action]);
        } catch (\Exception $e) {
            var_dump($e->getFile() . ': ' . $e->getLine());
            $output->writeln($e->getMessage());
        }
    }

    public function index() {
        echo 'index-crontab';
    }

    public function refund() {
        $orderId = '22961';
        $res = OrderService::getInstance()->frontRefundOrder($orderId, 20);
        exit;
    }

    //关闭未支付订单
    public function close() 
    {
        $time = time()- 10 * 60;
        $order = Db::name('order')->where('create_time','<', $time)->where('status', 0)->field('id')->select()->toArray();
        if ($order) {
            foreach ($order as $rs) {
                Db::name('order')->where('id', $rs['id'])->update(['status'=>-1,'cancel_time'=>time()]);
                $log = [
                    'order_id'=> $rs['id'],
                    'content' => '支付超时，关闭订单',
                    'admin_id' => 0,
                    'create_time' => time()
                ];
                Db::name('order_log')->insert($log);
                //还原班次车辆库存
                $shiftVehicle = Db::name('order_passenger')->where('order_id', $rs['id'])->field('count(1) count,shift_vehicle_id')->find();
                if ($shiftVehicle) {
                    Db::name('shift_vehicle')->where('id', $shiftVehicle['shift_vehicle_id'])->dec('buy_count', $shiftVehicle['count'])->update();
                }
            }
        }
    }

    // 关闭过期订单
    public function closeExpireOrder() {
        $time = time();
        $order = Db::name('order')->where('use_expire','<', $time)->where('status', 1)->field('id')->select()->toArray();
        if ($order) {
            foreach ($order as $rs) {
                Db::name('order')->where('id', $rs['id'])->update(['status'=>3,'cancel_time'=>time()]);
                $log = [
                    'order_id'=> $rs['id'],
                    'content' => '未核销已失效订单',
                    'admin_id' => 0,
                    'create_time' => time()
                ];
                Db::name('order_log')->insert($log);
            }
        }
    }
}